package com.example.hotdog.utils;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;

public class RSAUtils {

    static String  PUBLICKEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDNZftdLnrDNXnYshu9ePM5TKxIebCBvFa+YaHBI10lkhl+muiwhM35otbkV/DZYIvy7/iFGIFWMCH9UQw/tDpfF76YCHim0FLpfZfCtr+mIx/qBWvwGtJFipa+0+UZciIxe1EPycBME25Goht8fp9uwx1ZWwuR/HoAy2rIlkDFYwIDAQAB";



    /**
     * RSA公钥加密
     *
     * @param str       加密字符串
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    public static String publicKeyEncrypt(String str) throws Exception {
//        log.info("{}|RSA公钥加密前的数据|str:{}|publicKey:{}",point,str,publicKey);
        //base64编码的公钥
        byte[] decoded = Base64.getDecoder().decode(PUBLICKEY);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").
                generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String outStr = Base64.getEncoder().encodeToString(cipher.doFinal(str.getBytes("UTF-8")));
//        log.info("{}|公钥加密后的数据|outStr:{}",point,outStr);
        return outStr;
    }

    /**
     * RSA私钥解密
     *
     * @param str        加密字符串
     * @return 明文
     * @throws Exception 解密过程中的异常信息
     */
//    public static String privateKeyDecrypt(String str) throws Exception {
////        log.info("{}|RSA私钥解密前的数据|str:{}|privateKey:{}",point,str,privateKey);
//        //64位解码加密后的字符串
//        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
//        //base64编码的私钥
//        byte[] decoded = Base64.decodeBase64(PRIVATEKEY);
//        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
//                .generatePrivate(new PKCS8EncodedKeySpec(decoded));
//        //RSA解密
//        Cipher cipher = Cipher.getInstance("RSA");
//        cipher.init(Cipher.DECRYPT_MODE, priKey);
//        String outStr = new String(cipher.doFinal(inputByte));
////        log.info("{}|RSA私钥解密后的数据|outStr:{}",point,outStr);
//        return outStr;
//    }
}